package work.chenbo.springboot.elasticsearch.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.util.List;

@EnableConfigurationProperties({ElasticSearchProperties.class})
@Data
@Slf4j
@SpringBootConfiguration
public class ElasticSearchConfig {

    private final ElasticSearchProperties elasticSearchProperties;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient(){
        List<String> uris = elasticSearchProperties.getUris();

        HttpHost[] https = uris.stream().map(uri -> {
            String[] split = uri.split(":");
            String host = split[0];
            int port = Integer.parseInt(split[1]);
            return new HttpHost(host, port, "http");
        }).toArray(HttpHost[]::new);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(https));
        log.info("从{}链接ES客户端成功!!",uris);
        return restHighLevelClient;
    }
}
